package com.paradox.rpc.proxy;

import com.paradox.rpc.Carrier;
import com.paradox.rpc.Future;
import com.paradox.rpc.protocol.ClientFactory;
import com.paradox.rpc.protocol.ParadoxClient;
import io.netty.channel.Channel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class ProxyFactory implements InvocationHandler {

    private Class interfaceClass;

    public Object createProxy(Class interfaceClass){
        this.interfaceClass=interfaceClass;
        return Proxy.newProxyInstance(interfaceClass.getClassLoader(),new Class[]{interfaceClass},this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ParadoxClient client= ClientFactory.getClient("netty");
        Carrier carrier=new Carrier(UUID.randomUUID().toString(),interfaceClass.getName(),method.getName(),method.getParameterTypes(),args);
        Channel channel=client.start();
        Future<Object> future=new Future<Object>(channel);
        Future.responseReceiver.put(carrier.getId(),future);
        channel.writeAndFlush(carrier);
        return future.get();
    }
}
